package com.yunma.listen;

import com.common.bean.RequestInfoBean;
import com.common.util.SystemHWUtil;
import com.common.util.WindowUtil;
import com.io.hw.json.HWJacksonUtils;
import com.io.hw.json.JSONHWUtil;
import com.string.widget.util.ValueWidget;
import com.swing.component.ComponentUtil;
import com.swing.dialog.DialogUtil;
import com.swing.dialog.ProxyModifyResponseDialog;
import com.swing.dialog.toast.ToastMessage;
import com.swing.menu.MenuUtil2;
import com.swing.messagebox.GUIUtil23;
import com.swing.table.TableUtil3;
import com.yunma.autotest.AutoTestPanel;
import com.yunma.autotest.RequestPanel;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.JTextComponent;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

public class MyTableMenuListener implements ActionListener {

    public static final String ACTION_HIDE_OTHER_REQUEST = "隐藏其他请求";
    public static final String ACTION_maximize_TABLE = "最大化表格";
    private JTable jTable;
    private int selectedRow;
    private int selectedColumn;
    private RequestPanel currentRequestPanel;

    public MyTableMenuListener(JTable jTable, int selectedRow,
                               int selectedColumn, RequestPanel currentRequestPanel) {
        super();
        this.jTable = jTable;
        this.selectedRow = selectedRow;
        this.selectedColumn = selectedColumn;
        this.currentRequestPanel = currentRequestPanel;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        Object selectedChk = null;
        if (!ValueWidget.isNullOrEmpty(jTable)) {
            selectedChk = jTable.getValueAt(this.selectedRow, this.selectedColumn);
        }

//		System.out.println(command);
        if (command.equalsIgnoreCase(RequestPanel.ACTION_COMMAND_RUN)) {
            System.out.println("run");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    currentRequestPanel.requestAction(null);
                }
            }).start();
        } else if (command.equalsIgnoreCase(RequestPanel.ACTION_COMMAND_COPY_REQUEST_PARAMETER)) {
            System.out.println("获取请求要素");
            String requestBody = getRequestBody();
            if (!ValueWidget.isNullOrEmpty(requestBody)) {
                WindowUtil.setSysClipboardText(requestBody);
                ToastMessage.toast("已复制到剪切板", 3000);
            }
        } else if (command.equalsIgnoreCase(RequestPanel.ACTION_COMMAND_COPY_RESPONSE)) {
            System.out.println("获取应答");
            currentRequestPanel.requestAction(null);
            if (!ValueWidget.isNullOrEmpty(currentRequestPanel.getResponseJsonResult())) {
                WindowUtil.setSysClipboardText(currentRequestPanel.getResponseJsonResult());
                ToastMessage.toast("已复制到剪切板", 3000);
            }
        } else if (command.equalsIgnoreCase("清空结果")) {
        	/*currentRequestPanel.getResultTextPane().setText(SystemHWUtil.EMPTY);
        	currentRequestPanel.getRespTextArea_9().setText(SystemHWUtil.EMPTY);
        	currentRequestPanel.getJsonFormattedTextArea_9().setText(SystemHWUtil.EMPTY);*/
            currentRequestPanel.cleanUpTA();
        } else if (command.equalsIgnoreCase(MenuUtil2.ACTION_CREATE_MD5)) {
            if (!ValueWidget.isNullOrEmpty(selectedChk)) {
                if (selectedChk instanceof String) {
                    String source = (String) selectedChk;
                    String md5;
                    md5 = SystemHWUtil.getMD5(source, SystemHWUtil.CURR_ENCODING);
                    if (!ValueWidget.isNullOrEmpty(md5)) {
                        jTable.setValueAt(md5, selectedRow, selectedColumn);
                    }
                }
            }
        } else if (command.equalsIgnoreCase(MenuUtil2.ACTION_MD5_DECODE)) {
            if (!ValueWidget.isNullOrEmpty(selectedChk)) {
                if (selectedChk instanceof String) {
                    String md5 = (String) selectedChk;
                    String source;
                    source = SystemHWUtil.md5Map.get(md5);
                    if (ValueWidget.isNullOrEmpty(source)) {
                        ToastMessage.toast("暂无md5对应的原文", 3000, Color.red);
                    } else {
                        jTable.setValueAt(source, selectedRow, selectedColumn);
                    }
                }
            }
        } else if (command.equalsIgnoreCase(MenuUtil2.ACTION_STR_CLEANUP_CELL)) {
            if (selectedChk != null) {
                jTable.setValueAt(null, selectedRow, selectedColumn);
                ToastMessage.toast("已清空单元格(" + selectedRow + " ," + selectedColumn + ")", 3000);
            }
        } else if (command.equalsIgnoreCase(MenuUtil2.ACTION_URL_ENCODE)) {
            if (!ValueWidget.isNullOrEmpty(selectedChk)) {
                if (selectedChk instanceof String) {
                    String oldText = (String) selectedChk;
                    try {
                        String encodedStr = URLEncoder.encode(oldText, SystemHWUtil.CHARSET_UTF);
                        if (!ValueWidget.isNullOrEmpty(encodedStr)) {
                            jTable.setValueAt(encodedStr, selectedRow, selectedColumn);
                            ToastMessage.toast("URL编码成功", 3000);
                        }
                    } catch (UnsupportedEncodingException e1) {
                        e1.printStackTrace();
                        GUIUtil23.errorDialog(e1);
                    }
                }
            }

        } else if (command.equalsIgnoreCase(MenuUtil2.ACTION_URL_DECODE)) {
            if (!ValueWidget.isNullOrEmpty(selectedChk)) {
                if (selectedChk instanceof String) {
                    String oldText = (String) selectedChk;
                    try {
                        String encodedStr = URLDecoder.decode(oldText, SystemHWUtil.CHARSET_UTF);
                        if (!ValueWidget.isNullOrEmpty(encodedStr)) {
                            jTable.setValueAt(encodedStr, selectedRow, selectedColumn);
                            ToastMessage.toast("URL解码成功", 3000);
                        }
                    } catch (UnsupportedEncodingException e1) {
                        e1.printStackTrace();
                        GUIUtil23.errorDialog(e1);
                    }
                }
            }

        } else if (command.equalsIgnoreCase(MenuUtil2.ACTION_STR_COPY_CELL)) {//复制内容到剪切板
            if (!ValueWidget.isNullOrEmpty(selectedChk)) {
                if (selectedChk instanceof String) {
                    String oldText = (String) selectedChk;
                    WindowUtil.setSysClipboardText(oldText);
                    ToastMessage.toast("成功复制内容到剪切板", 3000);
                }
            }
        } else if (command.equalsIgnoreCase(MenuUtil2.ACTION_STR_PASTE_CELL)) {//把剪切板的内容黏贴到表格单元格中
            String oldText = WindowUtil.getSysClipboardText();
            if (!ValueWidget.isNullOrEmpty(oldText)) {
                jTable.setValueAt(oldText, selectedRow, selectedColumn);
            }
        } else if (command.equalsIgnoreCase("替换中文双引号")) {//把中文双引号转化英文双引号
            if (!ValueWidget.isNullOrEmpty(selectedChk)) {
                if (selectedChk instanceof String) {
                    String oldText = (String) selectedChk;
                    String content = ValueWidget.replaceChinaQuotes(oldText);
                    jTable.setValueAt(content, selectedRow, selectedColumn);
                }
            }
        } else if (command.equalsIgnoreCase("复制access_token")) {
            currentRequestPanel.copyAccessToken(null);
        } else if (command.equalsIgnoreCase("打开网页发送POST请求")) {
            currentRequestPanel.sendPostAction();
        } else if (command.equalsIgnoreCase("清空后再运行")) {
        	/*currentRequestPanel.getResultTextPane().setText(SystemHWUtil.EMPTY);
        	currentRequestPanel.getRespTextArea_9().setText(SystemHWUtil.EMPTY);
        	currentRequestPanel.getJsonFormattedTextArea_9().setText(SystemHWUtil.EMPTY);*/
            currentRequestPanel.cleanUpTA();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    currentRequestPanel.requestAction(null);
                }
            }).start();
        } else if (command.equalsIgnoreCase("复制请求panel")) {
            RequestInfoBean requestInfoBean = currentRequestPanel.getRequestInfoBean(true);
            RequestPanel RequestPanel = currentRequestPanel.autoTestPanel.addOneRequest(true, true);
            //如果复制panel,那么要设置请求ID为空,避免重复
            requestInfoBean.setRequestID(null);
            RequestPanel.resume(requestInfoBean, true);
            RequestPanel.initializePreRequestIdListbox();
        } else if (command.equalsIgnoreCase("删除当前请求panel")) {//删除当前请求panel
            int tabCount = currentRequestPanel.autoTestPanel.getTabbedPane_2().getComponentCount();
            if (tabCount == 1) {
                ToastMessage.toast("不允许删除最后一个页签", 2000, Color.red);
                return;
            }
            if (currentRequestPanel.autoTestPanel.getGlobalConfig().isNoConfirmOnDeleteRequestPane()
                    ||
                    JOptionPane.showConfirmDialog(null, "Are you sure to DELETE ?", "确认",
                            JOptionPane.OK_CANCEL_OPTION) == JOptionPane.OK_OPTION) {
                RequestInfoBean requestInfoBean = currentRequestPanel.getRequestInfoBean(false);
                currentRequestPanel.autoTestPanel.appendStr2LogFile(SystemHWUtil.DIVIDING_LINE + "删除当前请求panel :" + SystemHWUtil.CRLF +
                        HWJacksonUtils.getJsonP(requestInfoBean)
                        + SystemHWUtil.CRLF + SystemHWUtil.DIVIDING_LINE, true);
                currentRequestPanel.autoTestPanel.deleteCurrentPanel(currentRequestPanel);
            }
        } else if (command.equalsIgnoreCase(RequestPanel.ACTION_COMMAND_COPY_REQUEST_INFO)) {//拷贝当前请求panel的请求信息
            currentRequestPanel.copyRequestInfoAction();
        } else if (command.equalsIgnoreCase(RequestPanel.ACTION_COMMAND_PASTE_REQUEST_INFO)) {
            currentRequestPanel.pasteRequestInfoAction();
        } else if (command.equalsIgnoreCase("复制key:val")) {
            String key_val = WindowUtil.getSysClipboardText();
            if (!ValueWidget.isNullOrEmpty(key_val)) {
                String[] strs = key_val.split("[:=]");
                jTable.setValueAt(strs[0], this.selectedRow, 0);//第一列
                if (!ValueWidget.isNullOrEmpty(strs[1])) {
                    jTable.setValueAt(strs[1], this.selectedRow, 1);//第二列
                }
            }
        } else if (command.equalsIgnoreCase("rend table")) {
            currentRequestPanel.rendTable();
        } else if (command.equalsIgnoreCase("添加新请求")) {
            currentRequestPanel.autoTestPanel.addOneRequest(true, true);
        } else if (command.equalsIgnoreCase("clean table")) {//清空表格的单元格
            if (!ValueWidget.isNullOrEmpty(jTable)) {
                TableUtil3.cleanTableData(jTable, currentRequestPanel.getConfigParam());
                jTable.repaint();
            }
        } else if (command.equalsIgnoreCase("增加row高度")) {//
            if (!ValueWidget.isNullOrEmpty(jTable)) {
                int rowHeight = jTable.getRowHeight(this.selectedRow);
                int addedHeight = 60;
                jTable.setRowHeight(this.selectedRow, rowHeight + addedHeight);
                jTable.repaint();
                currentRequestPanel.addTableHeight(addedHeight);
                currentRequestPanel.getAutoTestPanel().updateUI2();
            }
        } else if (command.equalsIgnoreCase("减少row高度")) {
            if (!ValueWidget.isNullOrEmpty(jTable)) {
                int rowHeight = jTable.getRowHeight(this.selectedRow);
                if (rowHeight < 20) {
                    return;
                }
                jTable.setRowHeight(this.selectedRow, rowHeight - 20);
                jTable.repaint();
            }
        } else if (command.equals("最大化")) {
            DialogUtil.showMaximizeDialog(jTable);
            System.out.println("窗口关闭");
            currentRequestPanel.repaint();//necessary
        } else if (command.equals(ACTION_HIDE_OTHER_REQUEST)) {
            System.out.println(ACTION_HIDE_OTHER_REQUEST);
            AutoTestPanel autoTestPanel = currentRequestPanel.getAutoTestPanel();
            JTabbedPane tabbedPane_2 = autoTestPanel.getTabbedPane_2();
            if (tabbedPane_2.getTabCount() < 2) {
                System.out.println("不用执行");
                return;
            }
            int sum = autoTestPanel.getAllRequestPanelList().size();
            System.out.println("sum:" + sum);
            System.out.println("tabbedPane_2:" + tabbedPane_2.getTabCount());
            int selectedIndex = autoTestPanel.getGlobalInfo().getCurrentTabbedIndex();//autoTestPanel.getCurrentSelectedIndex();
            System.out.println("selectedIndex:" + selectedIndex);

            tabbedPane_2.removeAll();
            tabbedPane_2.addTab(currentRequestPanel.getRequestName(), null, currentRequestPanel, currentRequestPanel.getRequestId());
            tabbedPane_2.setSelectedIndex(tabbedPane_2.getTabCount() - 1);
            autoTestPanel.getGlobalInfo().setWillSave(false);
            ToastMessage.toast("后续的修改将不会保存", 2000, Color.RED);
        } else if (command.equals("最大化请求面板")) {//目的是隐藏最左边的"http 默认值"
            AutoTestPanel autoTestPanel = currentRequestPanel.getAutoTestPanel();
            autoTestPanel.getSplitPane().setDividerLocation(4);//最外层的split的左边的宽度
        } else if (command.equals("添加参数")) {
            currentRequestPanel.addParameter(null);
        } else if (command.equals("从剪切板添加参数")) {
            currentRequestPanel.addParameterClip();
        } else if (command.equals("删除参数")) {
            DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
            System.out.println("行数:" + tableModel.getRowCount());
            String parameterKey = TableUtil3.getTableCellValStr(tableModel.getValueAt(this.selectedRow, 0), currentRequestPanel.getConfigParam());
//            System.out.println(parameterKey);
            int result = JOptionPane.showConfirmDialog(null, "Are you sure to delete 参数\"" + parameterKey + "\" ?", "确认",
                    JOptionPane.OK_CANCEL_OPTION);
            if (result == JOptionPane.OK_OPTION) {
                tableModel.removeRow(this.selectedRow);
                tableModel.fireTableDataChanged();
//			jTable.setModel(tableModel);
                System.out.println("行数:" + tableModel.getRowCount());
                Object[][] dataObjs = TableUtil3.getParameter4Table(jTable).getComplexSwingComponent();
                currentRequestPanel.setTableData2(dataObjs);
                currentRequestPanel.adaptTableSize2(true, false/*isAdd*/, true/*isDel*/);
                currentRequestPanel.repaintTable();
            }
        } else if (command.equals("删除多个参数")) {
            int rowsNumToDel = ComponentUtil.getImageHeight(null, "请输入要删除的行数(从当前行开始向下):");
            if (rowsNumToDel > 0) {
//                int result = JOptionPane.showConfirmDialog(null, "Are you sure to delete " + rowsNumToDel + " 个参数 ?", "确认",
//                        JOptionPane.OK_CANCEL_OPTION);
//                if (result == JOptionPane.OK_OPTION) {
                DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
                for (int i = 0; i < rowsNumToDel; i++) {
                    if (this.selectedRow >= tableModel.getRowCount()) {
                        break;
                    }
                    tableModel.removeRow(this.selectedRow);
                }

                tableModel.fireTableDataChanged();
//			jTable.setModel(tableModel);
                System.out.println("行数:" + tableModel.getRowCount());
                Object[][] dataObjs = TableUtil3.getParameter4Table(jTable).getComplexSwingComponent();
                currentRequestPanel.setTableData2(dataObjs);
                currentRequestPanel.adaptTableSize2(true, false/*isAdd*/, true/*isDel*/);
                currentRequestPanel.repaintTable();
//                }
            }
        } else if (command.equals("删除全部参数")) {//删除全部请求参数
            DefaultTableModel tableModel = (DefaultTableModel) jTable.getModel();
            int rows = tableModel.getRowCount();
            for (int i = 0; i < rows; i++) {
                tableModel.removeRow(0);
            }
        } else if (command.equals("打开前置请求")) {
            currentRequestPanel.openPreRequestAction();
        } else if (command.equals("生成发送请求代码")) {
            currentRequestPanel.autoGenerateSendHttpCode(false);
        } else if (command.equals("生成发送请求代码python")) {
            currentRequestPanel.autoGenerateSendHttpPythonCode(false);
        } else if (command.equals("生成发送请求代码python并保存")) {
            currentRequestPanel.autoGenerateSendHttpPythonCode(true);
        } else if (command.equals("生成发送请求代码cURL")) {
            currentRequestPanel.autoGeneratecurlCode(false);
        } else if (command.equals("生成发送请求代码cURL(单行)")) {
            currentRequestPanel.autoGeneratecurlCode(true);
        } else if (command.equals("生成发送请求代码(更基础)")) {
            currentRequestPanel.autoGenerateSendHttpCode(true);
        } else if (command.equals("获取表格高度")) {
            int tableHeight = currentRequestPanel.getTableHeight();// currentRequestPanel.getParameterTable_1().getHeight();//0个行:0;<br>1个行:30;<br>2行:60;<br>3行:90
            GUIUtil23.alert("表格高度:" + tableHeight);
            System.out.println("表格高度:" + tableHeight);
        } else if (command.equals("获取tableScroll高度")) {
            int tableScrollHeight = currentRequestPanel.getTableScrollHeight();
            GUIUtil23.alert("tableScroll高度:" + tableScrollHeight);
            System.out.println("tableScroll高度:" + tableScrollHeight);
        } else if (command.equals("自适应表格split高度")) {
            currentRequestPanel.adaptTableSize2(true/* 很有必要,不能去掉 isFrameRepaint*/, false/*isAdd*/, false/*isDel*/);
            currentRequestPanel.minussplitPaneInnerLocation();
        } else if (command.equals("splitPane位置")) {
            System.out.println("splitPane位置");
            GUIUtil23.alert("splitPane位置:" + currentRequestPanel.getsplitPaneInnerLocation());
        } else if (command.equals("splitPane滚动条位置")) {
            System.out.println("splitPane滚动条位置");
            GUIUtil23.alert("splitPane滚动条位置:" + currentRequestPanel.getSanel_7JS2Height());
        } else if (command.equals("修改代理应答体")) {
            ProxyModifyResponseDialog dialog = new ProxyModifyResponseDialog(currentRequestPanel.autoTestPanel.getModifyResponseBodyBean());
//            dialog.setModifyResnseBodyBean(currentRequestPanel.autoTestPanel.getModifyResponseBodyBean());
            dialog.launch();
        } else if (command.equals("上传配置文件")) {
            System.out.println("上传配置文件");
        } else if (command.equals(MyTableMenuListener.ACTION_maximize_TABLE)) {
            DialogUtil.showMaximizeDialog(currentRequestPanel.getTableScroll(), false);
            currentRequestPanel.repaint();//necessary
        } else if (command.equals("复制请求要素为json")) {
            String requestBody = getRequestBody();
            String jsonResult = JSONHWUtil.parameter2Json(requestBody);
            WindowUtil.setSysClipboardText(jsonResult);
            ToastMessage.toast("复制json到剪切板", 2000);
        } else if (command.equals("获取textarea高度")) {
            Object cellVal = currentRequestPanel.getParameterTable_1().getValueAt(this.selectedRow, 1);
            JTextComponent textComponent = currentRequestPanel.getCellTextComponent(cellVal);
            ToastMessage.toast("height:" + textComponent.getHeight(), 3000);
            currentRequestPanel.resetTableRowHeight();
            currentRequestPanel.adaptTableSize2(true/* 很有必要,不能去掉 isFrameRepaint*/, false/*isAdd*/, false/*isDel*/);
        }
    }

    public String getRequestBody() {
        String requestBody = currentRequestPanel.getRequestBodyDataTA().getText();
        if (ValueWidget.isNullOrEmpty(requestBody)) {
            requestBody = currentRequestPanel.generateRequestBody(false);
        }
        return requestBody;
    }

}
